package com.bayss.core.util;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import net.sf.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WeixinApi {

	private static final Logger logger = LoggerFactory.getLogger(WeixinApi.class); 
	 
	private static CloseableHttpClient httpClient = HttpClients.createDefault();
	private static ObjectMapper objectMapper = new ObjectMapper();
	private static final HashFunction hashingMd5Function = Hashing.md5();
 
	/**微信企业转账url*/
    public static final String business_pay_url="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
	

	/**
	 * 获取小程序access token
	 * 
	 * @return token
	 */
	public static String getWeAppAccessToken() {
		String token = null;
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		// TODO
//		nvps.add(new BasicNameValuePair("appid", APPID));
		// TODO
//		nvps.add(new BasicNameValuePair("secret", SECRET));
		nvps.add(new BasicNameValuePair("grant_type", "client_credential"));

		try {
			String params = EntityUtils.toString(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
			HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?" + params);
			HttpResponse response = httpClient.execute(httpGet);
			Map<String, String> map = objectMapper.readValue(response.getEntity().getContent(), Map.class);
			logger.debug("getWeAppAccessToken result : " + map);
			token = map.get("access_token");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return token;
	}
	 

	// 检验文字
	public static boolean msg_sec_check(String content) {
		if(true){
			return true;
		}
		String accessToken = getWeAppAccessToken();
		String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN",
				accessToken);
		// 发起POST请求创建菜单
		Map<String, Object> map = new HashMap<>();
		map.put("content", content);
		String jsonString = JSONObject.fromObject(map).toString();
		JSONObject jsonObject = WeixinUtil.HttpRequest(url, "POST", jsonString);
		boolean bool = true;
		if (jsonObject != null) {
			if (0 != jsonObject.getInt("errcode")) {
				bool = false;
			}
		}
		return bool;
	}
 
}
